﻿/* 功能:  个人产品管理
 * 创建人：Kencery  创建时间：2018-2-3
 */
var ml = window.ml || {};
ml.admin = ml.admin || {};

ml.admin.productuser = (function () {
    var defaults = {
        listUrl: "/Product/ListUser",
        getListByMerchantIdUrl: "/ProductCategory/GetListByMerchantId",
        uploadUrl: "/Common/UploadImage",
        addUrl: "/Product/Add",
        editUrl: "/Product/Update",
        ualMarkUrl: "/Product/UalMark",
        delUrl: "/Product/Delete",
        detailUrl: "/Product/GetDetailById"
    };
    var opt = {};

    var columns = [{
        field: 'state',
        radio: true
    }, {
        title: '行号',
        field: 'number',
        align: 'center',
        hide: true,
        formatter: plscommon.tableNumber
    }, {
        title: '菜品ID',
        field: 'Id',
    }, {
        title: '菜品分类',
        field: 'ProductCategoryName',
        align: 'center',
    }, {
        title: '名称',
        field: 'Name',
        align: 'center',
    }, {
        title: '预览图',
        field: 'PreviewImg',
        align: 'center',
        formatter: function (value, rows, index) {
            return '<div><img src="' + value + '" style="width:40px;height:40px;"></div>';
        }
    }, {
        title: '原价',
        field: 'OriginalPrice',
        align: 'center',
    }, {
        title: '折扣价',
        field: 'DiscountPrice',
        align: 'center',
    }, {
        title: '销量',
        field: 'SalesVolume',
        align: 'center',
    }, {
        title: '好评率',
        field: 'PraiseRate',
        align: 'center',
    }, {
        title: '大小中份',
        field: 'Type',
        align: 'center',
        formatter: function (value, rows, index) {
            return returnType(value);
        }
    }, {
        title: '限购',
        field: 'IsLimitPurchase',
        align: 'center',
        formatter: function (value, rows, index) {
            var result = returnIsLimitPurchase(value);
            return '<div id="State_' + rows.Id + '">' + result + '</div>';
        }
    }, {
        title: '限购份数',
        field: 'LimitPurchaseCopies',
        align: 'center',
    }, {
        title: '上下架',
        field: 'UALMark',
        align: 'center',
        formatter: function (value, rows, index) {
            var result = returnUALMark(value);
            return '<div id="State_' + rows.Id + '">' + result + '</div>';
        }
    }, {
        title: '创建时间',
        field: 'CreateTime',
        align: 'center',
    }];

    var initTable = function () {
        plscommon.bootstraptable({
            id: "#productuserinfo",
            url: defaults.listUrl,
            queryParams: queryParams,
            uniqueId: "Id",
            columns: columns
        });
    }

    var queryParams = function (params) {
        return {
            offset: params.offset,             //后台计算显示数据信息
            pagesize: params.limit,            //每页显示多少行
            merchantname_search: $("#merchantname_search").val(),
            name_search: $("#name_search").val(),
            ualmark_search: $("#ualmark_search").val()
        };
    }

    var initDropDownList = function () {
        plscommon.dropDownList("#CategoryId", defaults.getListByMerchantIdUrl, 1, 1);
    }

    var clickEvent = function () {
        $("#btnQueryList").on("click", function () { btnQueryList(); });                      //按条件查询结果
        $("#btnReset").on("click", function () { btnReset(); });                              //清空文本框信息

        $("#file").on("change", function (e) { btnUploadFile(e) });                           //上传图片
        $("#btnAddDialog").on("click", function () { btnAddDialog(); });                      //添加弹层
        $("#btnEditDialog").on("click", function () { btnEditDialog(); });                    //修改弹层
        $("#btnAddOK").on("click", function () { btnAddOK(); });                              //添加修改实现

        $("#btnYesUalMarkDialog").on("click", function () { btnYesUalMarkDialog(); });        //上架弹出层
        $("#btnNoUalMarkDialog").on("click", function () { btnNoUalMarkDialog(); });          //下架弹出层
        $("#btnUalMarkOK").on("click", function () { btnUalMarkOK(); });                      //上下架操作

        $("#btnDelDialog").on("click", function () { btnDelDialog(); });                      //产品删除弹层
        $("#btnDeleteOK").on("click", function () { btnDeleteOK(); });                        //产品删除

        $("#btnDeltailDialog").on("click", function () { btnDeltailDialog(); });              //订单详情
    }

    var btnQueryList = function () {
        plscommon.refreshTable("productuserinfo");
    }

    var btnReset = function () {
        plscommon.resetFrom("formSearch");
    }

    var btnUploadFile = function (e) {
        var file = e.target.files[0] || e.dataTransfer.files[0];
        if (file) {
            var reader = new FileReader();
            reader.onload = function () { }
            reader.readAsDataURL(file);
        }
        var path = plscommon.uploadFile("post", defaults.uploadUrl, document.getElementById("file").files[0]);
        $("#PreviewImg").attr("src", path);
    }

    var btnAddDialog = function () {
        if (defaults.MerchantId == "") {
            plscommon.warningMessage("该商户还未配置店铺信息，不允许添加", 4000);
            return false;
        }

        $('#AddProductModal').modal();
        plscommon.resetFrom("ProductOperation");
        $("#HeadTitle").text("添加菜品");
        opt.type = 1;
        $("#PreviewImg").attr("src", "");
    }

    var btnEditDialog = function () {
        //必须选中一条才能弹出
        var data = plscommon.dialogWaring('productuserinfo', 'AddProductModal', 'ProductOperation');
        if (!data.Id) {
            return false;
        }

        $('#AddProductModal').modal();
        plscommon.resetFrom("ProductOperation");
        $("#HeadTitle").text("修改菜品");
        opt.type = 2;

        //赋值给控件信息(包括图片展示)
        $("#Id").val(data.Id);
        $("#Name").val(data.Name);
        $("#CategoryId").selectpicker("val", data.CategoryId);
        $("#OriginalPrice").val(data.OriginalPrice);
        $("#DiscountPrice").val(data.DiscountPrice);
        $("#Description").val(data.Description);
        $("#Tag").val(data.Tag);
        $("#Type").val(data.Type);
        $("#IsLimitPurchase").val(data.IsLimitPurchase);
        $("#LimitPurchaseCopies").val(data.LimitPurchaseCopies);
        $("#PreviewImg").attr("src", data.PreviewImg);
    }

    var btnAddOK = function () {
        //读取form表单中的值并且进行验证
        var data = plscommon.deleteByValue($("#ProductOperation").serializeArray(), "Id");
        data = plscommon.transitionArray(data);
        data.PreviewImg = $("#PreviewImg").attr("src");

        if (!checkData(data)) {
            return false;
        }

        $("#btnAddOK").prop("disabled", true);
        if (opt.type == 1) {
            plscommon.ajax_status({
                disableId: "btnAddOK",
                url: defaults.addUrl,
                type: "POST",
                data: data,
                success: function () {
                    if (this.status_code === 200) {
                        $('#AddProductModal').modal('hide');
                        plscommon.refreshTable("productuserinfo");
                    } else {
                        plscommon.warningMessage(this.status_message, 3000);
                    }
                }
            });
        } else {
            data.id = $("#Id").val();
            plscommon.ajax_status({
                disableId: "btnAddOK",
                url: defaults.editUrl,
                type: "POST",
                data: data,
                success: function () {
                    if (this.status_code === 200) {
                        $('#AddProductModal').modal('hide');
                        plscommon.refreshTable("productuserinfo");
                    } else {
                        plscommon.warningMessage(this.status_message, 3000);
                    }
                }
            });
        }
    }

    var btnYesUalMarkDialog = function () {
        var data = plscommon.dialogWaring('productuserinfo', 'UalMarkModal', 'ualMarkOperation');
        if (!data.Id) {
            return false;
        }

        //上架
        plscommon.resetFrom("ualMarkOperation");
        $("#ualMark_id").val(data.Id);
        $("#productName").text(data.Name);
        $("#productName_OK").text("上架该菜品(" + data.Name + ")");
        opt.UALMark = 1;
    }

    var btnNoUalMarkDialog = function () {
        var data = plscommon.dialogWaring('productuserinfo', 'UalMarkModal', 'ualMarkOperation');
        if (!data.Id) {
            return false;
        }

        //下架
        plscommon.resetFrom("ualMarkOperation");
        $("#ualMark_id").val(data.Id);
        $("#productName").text(data.Name);
        $("#productName_OK").text("下架该菜品(" + data.Name + ")");
        opt.UALMark = 0;
    }

    var btnUalMarkOK = function () {
        var data = plscommon.dialogWaring('productuserinfo', 'UalMarkModal', 'ualMarkOperation');
        if (opt.UALMark == 0 && data.UALMark == 0) {  //下架
            plscommon.warningMessage("该菜品已经是下架状态，不允许在下架", 3000);
            return false;
        }
        if (opt.UALMark == 1 && data.UALMark == 1) {  //上架
            plscommon.warningMessage("该菜品已经是上架状态，不允许在上架", 3000);
            return false;
        }

        $("#btnUalMarkOK").prop("disabled", true);
        plscommon.ajax_status({
            disableId: "btnUalMarkOK",
            url: defaults.ualMarkUrl,
            type: "POST",
            data: { Id: $("#ualMark_id").val(), UALMark: opt.UALMark },
            success: function () {
                if (this.status_code === 200) {
                    $('#UalMarkModal').modal('hide');
                    plscommon.refreshTable("productuserinfo");
                } else {
                    plscommon.warningMessage(this.status_message, 3000);
                }
            }
        });
    }

    var btnDelDialog = function () {
        var data = plscommon.dialogWaring('productuserinfo', 'DeleteModal', 'DeleteOperation');
        if (!data.Id) {
            return false;
        }

        $("#delete_id").val(data.Id);
        $("#Delete_Head_Title").text(data.Name);
        $("#Delete_Head_Title_OK").text(data.Name);
    }

    var btnDeleteOK = function () {
        var delete_id = $("#delete_id").val();
        if (!delete_id) {
            plscommon.warningMessage("请您选择需要删除的数据", 4000);
            return false;
        }

        $("#btnDeleteOK").prop("disabled", true);
        plscommon.ajax({
            disableId: "btnDeleteOK",
            url: defaults.delUrl,
            type: "POST",
            data: { id: delete_id },
            success: function () {
                $('#DeleteModal').modal('hide');
                $("#productuserinfo").bootstrapTable('refresh');
            }
        });
    }

    var btnDeltailDialog = function () {
        //必须选中一条才能弹出
        var data = plscommon.dialogWaring('productuserinfo', 'DetailModal', 'ProductDetail');
        if (!data.Id) {
            return false;
        }

        plscommon.ajax({
            url: defaults.detailUrl,
            type: "GET",
            data: { id: data.Id },
            success: function () {
                var data = this.data;
                $("#detail_platformname").val(data.ProductCategoryName);
                $("#detail_merchantname").val(data.MerchantName);
                $("#detail_name").val(data.Name);
                $("#detail_salesvolume").val(data.SalesVolume);
                $("#detail_originalprice").val(data.OriginalPrice);
                $("#detail_discountprice").val(data.DiscountPrice);
                $("#detail_description").val(data.Description);
                $("#detail_tag").val(data.Tag);
                $("#detail_praiserate").val(data.PraiseRate);
                $("#detail_type").val(returnType(data.Type));
                $("#detail_islimitpurchase").val(returnIsLimitPurchase(data.IsLimitPurchase));
                $("#detail_limitpurchasecopies").val(data.LimitPurchaseCopies);
                $("#detail_ualmark").val(returnUALMark(data.UALMark));
                $("#detail_createtime").val(data.CreateTime);
                $("#detail_previewimg").attr("src", data.PreviewImg);
            }
        });
    }

    var returnIsLimitPurchase = function (value) {
        var result = "";
        if (value == 0) {
            result = "不限购";
        }
        if (value == 1) {
            result = "限购";
        }
        return result;
    }

    var returnUALMark = function (value) {
        var result = "";
        if (value == 0) {
            result = "未上架";
        }
        if (value == 1) {
            result = "已上架";
        }
        return result;
    }

    var returnType = function (value) {
        var result = "";
        if (value == 1) {
            result = "大";
        }
        if (value == 2) {
            result = "中";
        }
        if (value == 3) {
            result = "小";
        }
        if (value == 4) {
            result = "其它";
        }
        return result;
    }

    var checkData = function (data) {
        if (!data.Name) {
            plscommon.warningMessage("菜品名称不能为空，请您检查", 3000);
            return false;
        }
        if (data.CategoryId == "-1") {
            plscommon.warningMessage("请您选择菜品分类", 3000);
            return false;
        }
        if (!data.OriginalPrice || !data.DiscountPrice) {
            plscommon.warningMessage("原价和折扣价不能为空,请您检查", 3000);
            return false;
        }
        if (data.IsLimitPurchase == 1) {  //如果选择限购必须填写限购数量
            if (data.LimitPurchaseCopies < 1 || data.LimitPurchaseCopies == undefined || data.LimitPurchaseCopies == null || data.LimitPurchaseCopies.length < 1) {
                plscommon.warningMessage("您选择了限购，请您输入限购数量大于0", 3000);
                return false;
            }
        }
        if (data.IsLimitPurchase == 0) {  //如果选择不限购不需要填写限购数量
            if (data.LimitPurchaseCopies.length == 0) {
                plscommon.warningMessage("您选择了不限购，请填写限购数量为0", 3000);
                return false;
            }
        }
        if (!data.PreviewImg) {
            plscommon.warningMessage("菜品预览图不能为空，请您检查", 3000);
            return false;
        }
        return true;
    }

    return {
        init: function (options) {
            $.extend(defaults, options || {});
            initTable();            //初始化Table表格
            clickEvent();           //触发事件
            initDropDownList();     //初始化下拉事件
        }
    };
}());